package com.settlement.system.controller;

import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.settlement.system.common.enums.*;
import com.settlement.system.common.exception.ServiceException;
import com.settlement.system.common.util.SecurityUtils;
import com.settlement.system.common.util.common.DateUtil;
import com.settlement.system.common.util.common.FasUtil;
import com.settlement.system.common.util.common.JsonUtil;
import com.settlement.system.common.util.common.SystemUserUtil;
import com.settlement.system.mapper.security.userdetails.SysUserDetails;
import com.settlement.system.model.entity.common.*;
import com.settlement.system.reply.ObjectDataResponse;
import com.settlement.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 统一账单明细 前端控制器
 *
 * @author Ximi
 * @since 2020-06-18
 */

@Api(tags = "统一报表-统一账单明细", description = "统一报表-统一账单明细")
@Slf4j
@RestController
@RequestMapping("/unification/bill_detail")
public class TblUnificationBillDetailController extends MergeApiExcelController<TblUnificationBillDetail, Map<String, Object>> {

    @Value("${system.export-root.path}")
    private String exportRootPath;

    @Resource
    private ITblUnificationBillDetailService tblUnificationBillDetailService;

    @Resource
    private ITblRrRecordProjectMainService tblRrRecordProjectMainService;

    @Resource
    private ITblReceiveRefundShopService tblReceiveRefundShopService;

    @Resource
    private ITblRrChannelService tblRrChannelService;


    @Resource
    private ITblRrBillTypeService tblRrBillTypeService;

    @Resource
    private ITblReceiveRefundSupplierService tblReceiveRefundSupplierService;


    @Resource
    private ITblRrVoucherTypeService tblRrVoucherTypeService;


    /*@Reference(version = "${dubbo.acs.api.version}", timeout = 6000)
    private OrderAduitApi orderAduitApi;*/

    @Override
    public IBaseService init() {
        return tblUnificationBillDetailService;
    }

    @Override
    public Class<?> getModelClass() {
        return TblUnificationBillDetail.class;
    }

    @Override
    protected void setParamsModel(Map<String, Object> model) {
        FasUtil.formatInQueryCondition(model,
                "shopNo", "shopAccount", "recordAccountProject",
                "unificationBillId", "originBillId", "companyNo", "billType",
                "billCategory", "shareOrNot", "beforeOrAfterTicket",
                "actionId", "thirdOrderNo", "channelNo", "serialNo", "summaryId",
                "voucherType", "threeChannelNo"
        );
        String accountingPeriod = (String) model.get("accountingPeriod");
        if (StringUtils.isNotEmpty(accountingPeriod)) {
            accountingPeriod = accountingPeriod.replace("月", "");
            Date accountingPeriodDate = DateUtil.parseToDate(accountingPeriod, "yyyyMM");
            String startOutDate = DateUtil.getDate(accountingPeriodDate, "yyyy-MM-dd");
            String endOutDate = DateUtil.getDate(DateUtil.getLastDayOfMonth(accountingPeriodDate), "yyyy-MM-dd");
            model.put("startOutDate", startOutDate);
            model.put("endOutDate", endOutDate);
            model.remove("accountingPeriod");
        }
        String batchNumber = (String) model.get("batchNumber");
        if (StringUtils.isNotEmpty(batchNumber)) {
            batchNumber = batchNumber.replace("，", ",");
            String[] split = batchNumber.split(",");
            if (split != null && split.length > 0) {
                List<String> batchNumberList = Arrays.asList(split);
                model.put("batchNumberList", batchNumberList);
            }
            model.remove("batchNumber");
        }
        super.setParamsModel(model);
    }

    @Override
    protected void setFootModel(Map<String, Object> result, Map<String, Object> model) throws ServiceException {
        result.put("foot", tblUnificationBillDetailService.getFoot(model));
    }

    @Override
    protected String verifyData(List<TblUnificationBillDetail> list) {
        for (TblUnificationBillDetail detail : list) {
            String message = verify(detail);
            if (!StringUtils.isEmpty(message)) {
                return message;
            }
        }
        return super.verifyData(list);
    }


    /**
     * 验证数据
     *
     * @param detail
     * @return
     */
    private String verify(TblUnificationBillDetail detail) {


        if (StringUtils.isEmpty(detail.getChannelName())) {
            return JsonUtil.getJsonOrToString(detail) + ":渠道不能为空";
        }
        String channelNo = tblRrChannelService.getNoByName(detail.getChannelName());
        if (StringUtils.isEmpty(channelNo)) {
            return JsonUtil.getJsonOrToString(detail) + ":渠道名称不对";
        }
        detail.setChannelNo(channelNo);

        Integer problemDesc = UnificationProblemDescEunm.encode(detail);
        detail.setProblemDesc(problemDesc);

        if (problemDesc == 0 || problemDesc == UnificationProblemDescEunm.bill_amount.getNo()) {
            detail.setStatus(UnificationStatusEunm.complete_match.getNo());
        } else {
            detail.setStatus(UnificationStatusEunm.no_match.getNo());
        }
        return null;
    }

    @ApiOperation("匹配")
    @RequestMapping(value = "refresh", method = {RequestMethod.POST})
    @ResponseBody
    protected ObjectDataResponse refresh(@RequestBody Map<String, Object> model, HttpServletRequest request) {
        try {
            model.put("status", UnificationStatusEunm.no_match.getNo());
            setParamsModel(model);
            String message = tblUnificationBillDetailService.refresh(model);
            if (StringUtils.isEmpty(message)) {
                return new ObjectDataResponse(ReturnStatusEnum.REQUEST_SUCCESS);
            } else {
                return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL.getValue(), message);
            }
        } catch (Exception ex) {
            log.info("更新数据异常", ex);
            return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL);
        }
    }

    @ApiOperation("生成账单汇总")
    @RequestMapping(value = "billSummary", method = {RequestMethod.POST})
    @ResponseBody
    protected ObjectDataResponse billSummary(@RequestBody Map<String, Object> model, HttpServletRequest request) {
        try {
            setParamsModel(model);
            String message = tblUnificationBillDetailService.billSummary(model);
            if (StringUtils.isEmpty(message)) {
                return new ObjectDataResponse(ReturnStatusEnum.REQUEST_SUCCESS);
            } else {
                return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL.getValue(), message);
            }
        } catch (Exception ex) {
            log.info("更新数据异常", ex);
            return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL);
        }
    }

    @Override
    @PostMapping("import")
    @CacheEvict(cacheNames = {
            "closeAccountByThreeChannelNoAndShopAccount", "rrRecordProject",
            "getChargeProjectByRecordAccountProject",
            "rrOrAccountByLoginAccount", "rrShopByShopNo",
            "getUnrepeatableVoucherTypes", "getByAccountBookShortNameAndSupplierName",
            "getByChannelNoAndBillTypeAndOriginBillProject"},
            allEntries = true, beforeInvocation = true)
    public ObjectDataResponse importFile(MultipartFile file, HttpServletRequest request) {
        return super.importFile(file, request);
    }

    @Override
    public String verifyImportObject(TblUnificationBillDetail detail, AnalysisContext analysisContext) {
        if (StringUtils.isEmpty(detail.getUnificationBillId())) {
            return "统一账单ID不能为空";
        }

        if (StringUtils.isEmpty(detail.getThirdOrderNo()) &&
                StringUtils.isEmpty(detail.getOriginBillProject()) &&
                StringUtils.isEmpty(detail.getRecordAccountProject()) &&
                StringUtils.isEmpty(detail.getActionId()) &&
                StringUtils.isEmpty(detail.getShopNo())) {
            return "外部订单号,原始账单项目,记账项目,活动ID,零售店铺编码不能同时为空";
        }
        Map<String, Object> params = new HashMap<>(16);
        try {
            params.put("unificationBillId", detail.getUnificationBillId());
            setParamsModel(params);
            String message = tblUnificationBillDetailService.checkIfCloseAccount(params);
            return message;
        } catch (ServiceException e) {
            log.error("An exception occurred in TblUnificationBillDetailController.verifyImportObject", e);
            return "发生异常";
        }
    }

    void setDetail(TblUnificationBillDetail detail) throws ServiceException {

        String billTypeNo = detail.getBillTypeNo();
        if (StringUtils.isNotEmpty(billTypeNo)) {
            String billCategoryByNo = tblRrBillTypeService.getBillCategoryByNo(billTypeNo);
            detail.setBillCategory(billCategoryByNo);
        }

        String voucherType = detail.getVoucherType();
        if (StringUtils.isNotEmpty(voucherType)) {
            String shareOrNot = voucherType;
            String beforeOrAfterTicket = voucherType;
            List<String> strings = Arrays.asList(voucherType.split(","));
            for (String string : strings) {
                String beforeOrAfterTicketStr = tblRrVoucherTypeService.getBeforeOrAfterTicket(string);
                if (StringUtils.isNotEmpty(beforeOrAfterTicketStr)) {
                    beforeOrAfterTicket = beforeOrAfterTicket.replace(string, beforeOrAfterTicketStr);
                } else {
                    beforeOrAfterTicket = null;
                    break;
                }
            }
            for (String string : strings) {
                String shareOrNotStr = tblRrVoucherTypeService.getShareOrNot(string);
                if (StringUtils.isNotEmpty(shareOrNotStr)) {
                    shareOrNot = shareOrNot.replace(string, shareOrNotStr);
                } else {
                    shareOrNot = null;
                    break;
                }
            }
            detail.setBeforeOrAfterTicket(beforeOrAfterTicket);
            detail.setShareOrNot(shareOrNot);
        }
    }

    /**
     * @param detail 原数据
     * @param data   导入的数据
     * @return
     * @throws ServiceException
     */
    String setDetailByData(TblUnificationBillDetail detail, TblUnificationBillDetail data) throws ServiceException {
        if (StringUtils.isNotBlank(data.getShopNo())) {
            detail.setShopNo(data.getShopNo());
        }
        if (StringUtils.isNotBlank(detail.getShopNo())) {
            TblReceiveRefundShop shop = tblReceiveRefundShopService.getByShopNo(detail.getShopNo());
            if (shop != null) {
                detail.setNcShopNo(shop.getNcShopNo());
                detail.setNcShopName(shop.getNcShopName());
                detail.setShopName(shop.getShopName());
                detail.setNcDeptNo(shop.getNcDeptNo());
                detail.setCompanyNo(shop.getNcEnterAccountBody());
                //线下打款的，不更新渠道
                if (!ChannelEnum.OR.getNo().equals(detail.getChannelNo())) {
                    detail.setNcChannelName(shop.getNcChannelName());
                    detail.setChannelName(shop.getChannelName());
                    detail.setChannelNo(shop.getChannelNo());
                }


                final String unionPayBillTypePrefix = "银联";
                final String none = "NONE";
                if (!ChannelEnum.OR.getName().equals(detail.getChannelName())) {
                    if (detail.getChannelName().equals(ChannelEnum.YG.getName()) && BillTypeEnum.YG_WX.getName().equals(detail.getBillType())) {
                        detail.setNcVirtualAccount("03001:虚拟账户");
                    } else {
                        if (detail.getBillType() != null) {
                            if (BillTypeEnum.convertToName(detail.getBillType()).contains(unionPayBillTypePrefix)) {
                                detail.setNcVirtualAccount(none);
                            }
                        } else {
                            detail.setNcVirtualAccount(shop.getNcVirtualAccount());
                        }
                    }
                }
            } else {
                log.info("没匹配到shopNo：" + detail.getShopNo());
                if (StrUtil.isNotEmpty(data.getShopNo())) {
                    return "[零售店铺编码]=" + detail.getShopNo() + " 在【RR-店铺设置】中不存在";
                }
            }
        }
        if (StringUtils.isNotBlank(data.getSupplierName())) {
            detail.setSupplierName(data.getSupplierName());
            String ncEnterAccountBody = detail.getCompanyNo();
            TblReceiveRefundSupplier supplier = tblReceiveRefundSupplierService.
                    getByAccountBookShortNameAndSupplierName(ncEnterAccountBody, detail.getSupplierName());
            if (supplier != null) {
                detail.setNcSupplierRecord(supplier.getNcSupplierRecord());
            } else {
                return "[入账主体]" + ncEnterAccountBody + "+[供应商名称]" + detail.getSupplierName() + " 在【RR-供应商设置】里不存在";
            }
        }
        if (StringUtils.isNotBlank(data.getThirdOrderNo())) {
            detail.setThirdOrderNo(data.getThirdOrderNo().replace("空", "NONE"));
        }
        if (StringUtils.isNotBlank(data.getRecordAccountProject())) {
            detail.setRecordAccountProject(data.getRecordAccountProject());
        }
        if (StringUtils.isNotBlank(data.getOriginBillProject())) {
            detail.setOriginBillProject(data.getOriginBillProject());
            if (StrUtil.isNotBlank(detail.getOriginBillProject())) {
                String recordProjectMain = tblRrRecordProjectMainService.
                        getByChannelNoAndBillTypeAndOriginBillProject(detail.getChannelNo(), detail.getBillType(), detail.getOriginBillProject());
                if (StrUtil.isEmpty(recordProjectMain)) {
                    return "[渠道]" + detail.getChannelName() + "[账单类型]" + detail.getBillType() + "+[原始账单项目]" + detail.getOriginBillProject() + " 在【RR-记账项目】中不存在";
                }
            }
        }
        if (StringUtils.isNotBlank(data.getActionId())) {
            detail.setActionId(data.getActionId());
        }
        return null;
    }

    @Override
    protected void saveData(List<TblUnificationBillDetail> datas) throws ServiceException {
        tblUnificationBillDetailService.updateMatch(datas);
    }

    private String validateStatus(List<TblUnificationBillDetail> datas) throws ServiceException {
        int totalCount = datas.size();
        int pageSize = 1000;
        int totalPage = PageUtil.totalPage(totalCount, pageSize);
        for (int i = 1; i <= totalPage; i++) {
            int start = pageSize * (i - 1);
            int end = start + pageSize;
            if (end > totalCount) {
                end = totalCount;
            }
            List<TblUnificationBillDetail> details = datas.subList(start, end);
            List<String> collect = details.stream().map(TblUnificationBillDetail::getUnificationBillId).collect(Collectors.toList());
            String s = com.settlement.system.common.util.common.StrUtil.toString(collect.toArray());
            Map<String, Object> params = new HashMap<>();
            params.put("multiNotStatus", "NM,CM");
            params.put("unificationBillId", s);
            FasUtil.formatInQueryCondition(params, "multiNotStatus", "unificationBillId");
            TblUnificationBillDetail detail = tblUnificationBillDetailService.selectOneByParam(params);
            if (detail != null) {
                return "统一账单ID=" + detail.getUnificationBillId() + "，状态不是未匹配 或完成匹配的，不允许更新数据。";
            }
        }

        return null;

    }

    @Override
    protected String validateAllDate(List<TblUnificationBillDetail> datas) {
        try {
            String message = validateStatus(datas);
            if (StringUtils.isNotEmpty(message)) {
                return message;
            }

            for (int i = 0; i < datas.size(); i++) {
                TblUnificationBillDetail data = datas.get(i);
                Map<String, Object> map = new HashMap<>(16);
                map.put("unificationBillId", data.getUnificationBillId());
                setParamsModel(map);
                List<TblUnificationBillDetail> temps = tblUnificationBillDetailService.selectByParam(map);
                if (!temps.isEmpty()) {
                    String str = "";

                    TblUnificationBillDetail detail = temps.get(0);

                    String s = setDetailByData(detail, data);
                    if (StrUtil.isNotEmpty(s)) {
                        return "第" + (i + 2) + "行数据" + s;
                    }

                    if (StringUtils.isNotBlank(detail.getRecordAccountProject()) && StringUtils.isNotBlank(detail.getChannelNo())) {
                        String billType = detail.getBillType();
                        //刷新稽核标识 是否参与记账 凭证类型这几个字段，从配置表中
                        List<TblRrRecordProjectMain> types = tblRrRecordProjectMainService.
                                getUnrepeatableVoucherTypes(detail.getRecordAccountProject(), detail.getChannelNo(), billType);
                        if (!types.isEmpty()) {
                            List<String> typeList = new ArrayList<>();
                            for (TblRrRecordProjectMain type : types) {
                                if (StringUtils.isNotEmpty(type.getVoucherType()) && !str.contains(type.getVoucherType())) {
                                    typeList.add(type.getVoucherType());
                                }
                            }
                            Set<String> set = sort(typeList);

                            for (String type : set) {
                                str += (type + ",");
                            }

                            if (str.endsWith(",")) {
                                str = str.substring(0, str.length() - 1);
                            }
                            detail.setVoucherType(str);
                            detail.setIsJoinRecordAccount(types.get(0).getIsJoinRecordAccount());
                            detail.setAuditMark(types.get(0).getAuditMark());
                        } else {
                            if (StringUtils.isNotBlank(data.getRecordAccountProject())) {
                                return "第" + (i + 2) + "行数据" + "[记账项目]" + detail.getRecordAccountProject() + "+[渠道]" + detail.getChannelName() + "+[账单类型]" + billType + "在【RR-记账项目】中不存在";
                            }
                        }
                    }

                    setDetail(detail);

                    if (StringUtils.isNotBlank(detail.getRecordAccountProject())) {
                        //刷新NC_收费项目
                        String chargeProject = tblRrRecordProjectMainService.
                                getChargeProjectByRecordAccountProject(detail.getRecordAccountProject(), detail.getChannelNo());
                        detail.setNcChargeProject(chargeProject);
                    }

                    datas.set(i, detail);
                }
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            //throw new RuntimeException(ex);
            return "导入校验出错";
        }
        return null;
    }

    /**
     * 按照字符串的长度从小到大排序
     *
     * @param strs
     * @return
     */
    private static Set<String> sort(List<String> strs) {

        Set<String> set = new TreeSet<>(new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                int num = Integer.valueOf(s1.length()).compareTo(Integer.valueOf(s2.length()));
                //如果长度相等，则根据内容排序
                if (num == 0) {
                    return s1.compareTo(s2);
                }
                return num;
            }
        });

        for (String s : strs) {
            set.add(s);
        }

        return set;

    }

    /*@Override
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
            Map<String, Object> params = buildParam(request);
            setParamsModel(params);
            String fileName = "RR-统一账单明细";
            String path = exportRootPath + System.currentTimeMillis() + "/";
            CsvExportUtil.createCsv()
                    .headClass(TblUnificationBillDetail.class)
                    .fileName(fileName)
                    .model(CsvExportBuilder.MULTI_ZIP_MODEL)
                    .parentPath(path)
                    .csvDatas(new DateSpiltCsvDatas(tblUnificationBillDetailService, params))
                    .export(request, response);
    }*/

    @Override
    @ApiOperation("选单批量删除")
    @RequestMapping(value = "batchDelete", method = {RequestMethod.POST})
    @ResponseBody
    protected ObjectDataResponse batchDelete(@RequestBody List<TblUnificationBillDetail> deleteList, HttpServletRequest request) {
        try {
            ObjectDataResponse rsp = new ObjectDataResponse();
            if (!validateDeleteData(deleteList, rsp)) {
                return rsp;
            }

            tblUnificationBillDetailService.batchDelete(deleteList);
            sendOrderAduitMessage(deleteList);
            return new ObjectDataResponse(ReturnStatusEnum.REQUEST_SUCCESS.getValue(), "删除成功！");
        } catch (Exception e) {
            log.error("批量删除统一账单异常", e);
            return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL.getValue(), "删除异常，请联系管理员！");
        }
    }

    private void sendOrderAduitMessage(List<TblUnificationBillDetail> deleteList) {
        for (TblUnificationBillDetail detail : deleteList) {
            if (StringUtils.isNotEmpty(detail.getThirdOrderNo()) && StringUtils.isNotEmpty(detail.getShopNo())) {
                try {
                    /*orderAduitApi.asyncOrderAudit(detail.getThirdOrderNo(), detail.getShopNo());*/
                } catch (Exception e) {
                    log.error("刪除统一账单，推送消息异常", e);
                }
            }
        }
    }

    private boolean validateDeleteData(List<TblUnificationBillDetail> deleteList, ObjectDataResponse rsp) throws ServiceException {
        Map<String, Object> params = new HashMap<>(16);
        try {
            SysUserDetails user = SecurityUtils.getUser();;
            String username = user.getUsername();
            for (TblUnificationBillDetail detail : deleteList) {
                //3、【RR-统一账单明细】的数据状态是“完成推送NC凭证”，不可删除，只能通过【RR-NC凭证明细】撤销。
                if (UnificationStatusEunm.complete_push_nc.getNo().equals(detail.getStatus())) {
                    rsp.setMessage("数据状态是“" + UnificationStatusEunm.complete_push_nc.getName() + "”，不可删除。请检查！");
                    rsp.setCode(ReturnStatusEnum.CHECK_FAILURE.getValue());
                    return false;
                }

                //1、【RR-统一账单明细】的数据状态是“完成匹配”，且为RPA下载的账单生成的统一账单，才可勾选删除。
                if (!detail.getOriginBillId().contains("MK-") && detail.getCreateUser().equals("robot")) {
                    rsp.setMessage("RPA下载的账单生成的统一账单，都不可勾选删除。请检查！");
                    rsp.setCode(ReturnStatusEnum.CHECK_FAILURE.getValue());
                    return false;
                }
                //2、【RR-统一账单明细】的数据状态是“完成匹配”，且为手工导入的统一账单，只能导入者才可勾选删除。
                if (detail.getOriginBillId().contains("MK-") && !detail.getCreateUser().equals("robot")) {
                    if (!(UnificationStatusEunm.no_match.getNo().equals(detail.getStatus())
                            || UnificationStatusEunm.complete_match.getNo().equals(detail.getStatus())
                    )
                            || !detail.getCreateUser().equals(username)
                    ) {
                        rsp.setMessage("手工导入的统一账单，数据状态是“未匹配”或“完成匹配”，只能导入者才可勾选删除。请检查！");
                        rsp.setCode(ReturnStatusEnum.CHECK_FAILURE.getValue());
                        return false;
                    }
                }

                params.put("id", detail.id);
                if (tblUnificationBillDetailService.validateCloseDate(params) > 0) {
                    rsp.setMessage("删除了锁帐之后的数据，请检查！");
                    rsp.setCode(ReturnStatusEnum.CHECK_FAILURE.getValue());
                    return false;
                }
            }
            return true;
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }


    @ApiOperation("按批次号批量删除")
    @RequestMapping(value = "delBatchNumber", method = {RequestMethod.POST})
    @ResponseBody
    protected ObjectDataResponse batchDelete(HttpServletRequest request, @RequestBody Map<String, Object> paramModel) {
        final String strBatchNumber = "batchNumber";

        if (paramModel.get(strBatchNumber) == null || StringUtils.isEmpty(String.valueOf(paramModel.get(strBatchNumber)))) {
            return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE.getValue(), "批次号不能为空，请检查！");
        }
        try {
            setParamsModel(paramModel);

            int completePushNcCount =
                    tblUnificationBillDetailService.selectCountByBatchNumberAndCpnStatus(paramModel);
            if (completePushNcCount > 0) {
                return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE.getValue(),
                        "数据状态是“" + UnificationStatusEunm.complete_push_nc.getName() + "”，不可删除。请检查！");
            }

            int notCompleteMatchCount =
                    tblUnificationBillDetailService.selectCountByBatchNumberAndNotCmStatus(paramModel);
            if (notCompleteMatchCount > 0) {
                return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE.getValue(),
                        "手工导入的统一账单，数据状态是“未匹配”或“完成匹配”，只能导入者才可删除。请检查！");
            }

            SysUserDetails user = SecurityUtils.getUser();;
            String username = user.getUsername();
            paramModel.put("notCreateUser", username);
            int notCreateUserCount =
                    tblUnificationBillDetailService.selectCountByBatchNumberAndNotCreateUser(paramModel);
            if (notCreateUserCount > 0) {
                return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE.getValue(),
                        "手工导入的统一账单，数据状态是“未匹配”或“完成匹配”，只能导入者才可删除。请检查！");
            }

            if (tblUnificationBillDetailService.validateCloseDate(paramModel) > 0) {
                return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE.getValue(), "删除了锁帐之后的数据，请检查！");
            }
            boolean flag = tblUnificationBillDetailService.deleteByBatchNumber(paramModel);
            if (flag) {
                List<TblUnificationBillDetail> needSendDate = tblUnificationBillDetailService.getDeleteDate(paramModel);
                if (needSendDate != null && needSendDate.size() > 0) {
                    for (TblUnificationBillDetail detail : needSendDate) {
                        if (StringUtils.isNotEmpty(detail.getThirdOrderNo()) && StringUtils.isNotEmpty(detail.getShopNo())) {
                            /*orderAduitApi.asyncOrderAudit(detail.getThirdOrderNo(), detail.getShopNo());*/
                        }
                    }
                }
                return new ObjectDataResponse(ReturnStatusEnum.REQUEST_SUCCESS);
            }
            return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL.getValue(), "删除失败，无符合数据");
        } catch (Exception e) {
            log.error("批量删除统一账单异常", e);
            return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL.getValue(), "删除异常，请联系管理员！");
        }
    }

    /**
     * 通过外部订单号获取账单金额汇总
     *
     * @param params
     * @return
     */
    @ApiOperation(value = "统一账单-获取账单金额汇总")
    @RequestMapping(value = "/api/getBillAmount", method = RequestMethod.POST)
    public ObjectDataResponse<Map> getBillAmount(@RequestBody UnificationBillApiParams params) {
        try {
            ObjectDataResponse response = null;
            if (StringUtils.isBlank(params.getThirdOrderNo())) {
                return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE.getValue(), "外部订单号不能为空");
            }

            Map<String, Object> map = new HashMap<>(16);
            map.put("thirdOrderNo", params.getThirdOrderNo());
            setParamsModel(map);
            List<TblUnificationBillDetail> list = tblUnificationBillDetailService.selectByParam(map);
            BigDecimal billAmount = new BigDecimal("0");
            for (TblUnificationBillDetail detail : list) {
                if ("Y".equals(detail.getAuditMark()) && !"退运费".equals(detail.getRecordAccountProject())) {
                    billAmount = billAmount.add(detail.getBillAmount() == null ? new BigDecimal("0") : detail.getBillAmount());
                }
            }
            map = new HashMap<>(16);
            map.put("billAmount", billAmount);
            map.put("thirdOrderNo", params.getThirdOrderNo());
            return new ObjectDataResponse<Map>(map, 200, "success");
        } catch (Exception ex) {
            log.error("获取账单金额汇总出错", ex);
            return new ObjectDataResponse(500, "服务器异常");
        }
    }

    @Override
    protected ObjectDataResponse getPageList(HttpServletRequest request, @RequestBody BasePager<Map<String, Object>> model) {
        Map<String, Object> result = new HashMap<>(16);
        try {
            insetMenuMemory(model.getModel());
            processModel(model);
            setParamsModel(model.getModel());
            //int count = baseService.selectCount(model.getModel());
            List<TblUnificationBillDetail> rows = tblUnificationBillDetailService.selectByPage(new SinglePage(model), model.getModel(),
                    model.getOrderByField(), model.getOrderBy());
            result.put("rows", rows);
            //TblUnificationBillDetail foot = tblUnificationBillDetailService.getFoot(model.getModel());
            result.put("total", 0);
            //setFootModel(result, model.getModel());
            result.put("foot", new TblUnificationBillDetail());
        } catch (Exception ex) {
            log.error("获取列表出错", ex);
            return new ObjectDataResponse(500, "获取列表失败，请联系管理员！");
        }
        return new ObjectDataResponse<Map>(result, 200, "获取列表成功");
    }

    @ApiOperation("汇总查询")
    @RequestMapping(value = "getFoot", method = {RequestMethod.POST})
    @ResponseBody
    protected ObjectDataResponse getFoot(HttpServletRequest request, @RequestBody BasePager<Map<String, Object>> model) {
        Map<String, Object> result = new HashMap<>(16);
        try {
            insetMenuMemory(model.getModel());
            processModel(model);
            setParamsModel(model.getModel());
            //int count = baseService.selectCount(model.getModel());
            //List<TblUnificationBillDetail> rows = tblUnificationBillDetailService.selectByPage(new SinglePage(model), model.getModel(),
            //        model.getOrderByField(), model.getOrderBy());
            //result.put("rows", rows);
            TblUnificationBillDetail foot = tblUnificationBillDetailService.getFoot(model.getModel());
            result.put("total", foot.getTotal());
            result.put("foot", foot);
        } catch (Exception ex) {
            log.error("获取列表出错", ex);
            return new ObjectDataResponse(500, "获取列表失败，请联系管理员！");
        }
        return new ObjectDataResponse<Map>(result, 200, "获取列表成功");
    }

    /*private void formatData(List<TblUnificationBillDetail> datas) {
        if(!CollectionUtils.isEmpty(datas)){
            for (TblUnificationBillDetail detail : datas) {
                {
                    String shareOrNot = detail.getShareOrNot();
                    if(org.apache.commons.lang3.StringUtils.isNotEmpty(shareOrNot)){
                        String[] split = shareOrNot.split(",");
                        List<String> collect = Arrays.asList(shareOrNot.split(",")).stream().map(s -> {
                            return ShareOrNotEnum.getNameByNo(s);
                        }).collect(Collectors.toList());

                        String shareOrNotStr = collect.toString().replaceAll("[\\[\\]\\s]", "");
                        detail.setShareOrNot(shareOrNotStr);
                    }
                }
                String beforeOrAfterTicket = detail.getBeforeOrAfterTicket();
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(beforeOrAfterTicket)){
                    String[] split = beforeOrAfterTicket.split(",");
                    List<String> collect = Arrays.asList(beforeOrAfterTicket.split(",")).stream().map(s -> {
                        return BeforeOrAfterTicketEnum.getNameByNo(s);
                    }).collect(Collectors.toList());

                    String beforeOrAfterTicketStr = collect.toString().replaceAll("[\\[\\]\\s]", "");
                    detail.setBeforeOrAfterTicket(beforeOrAfterTicketStr);
                }
            }
        }
    }*/

}

